package com.android.tianyuanyouxuan.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.android.tianyuanyouxuan.bean.Goods;
import com.android.tianyuanyouxuan.databinding.FragmentHomeBinding;
import com.android.tianyuanyouxuan.presenter.HomePresenter;
import com.android.tianyuanyouxuan.ui.activity.GoodsDetailsActivity;
import com.android.tianyuanyouxuan.ui.activity.SearchActivity;
import com.android.tianyuanyouxuan.ui.adapter.HomeAdapter;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding viewBinding;

    private HomePresenter homePresenter = new HomePresenter();
    private HomeAdapter homeAdapter = new HomeAdapter();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        viewBinding = FragmentHomeBinding.inflate(LayoutInflater.from(requireContext()));
        return viewBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewBinding.rvList.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        viewBinding.rvList.setAdapter(homeAdapter);
        homeAdapter.setNewInstance(homePresenter.getGoodsList());
        homeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Intent intent = new Intent(requireContext(), GoodsDetailsActivity.class);
                Goods goods = homeAdapter.getItem(position);
                intent.putExtra("data", GsonUtils.toJson(goods));
                startActivity(intent);
            }
        });
        viewBinding.llSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtils.startActivity(SearchActivity.class);
            }
        });
    }

}
